package ssi.staaar;

import ssi.peeno.model.Message;
import ssi.staar.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

public class ReadMessageActivity extends Activity {
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.readmessage);
		Log.d("[READMESSAGE]", "Started");
		Intent self = this.getIntent();
		Message m = (Message) self.getSerializableExtra("Message.Current");
		m.setText(retrieveMessageText(m.getId()));
		TextView mainText = (TextView)findViewById(R.id.readMessageText1);
		if (m.isMyMessage()) {
			Log.d("[READMESSAGE]", "My Message");
			mainText.setText("This is your message");
			if (m.getType().equals("CRYPT")) {
				Log.d("[READMESSAGE]", "My Crypted Message");
				String message = decryptMyMessage(m);
				m.setText(message);
			}
		} else {
			if (m.isPrivate()) {
				Log.d("[READMESSAGE]", "User Private Message");
				mainText.setText("This is a private message");
				String message = decryptPrivateMessage(m);
				m.setText(message);
			}
			else {
				mainText.setText("This is a public message");
				Log.d("[READMESSAGE]", "User Public Message");
				if (m.getType().equals("CRYPT")) {
					Log.d("[READMESSAGE]", "User Public Crypted Message");
					String message = decryptMessage(m);
					m.setText(message);
				}	
			}
		}
		EditText author = (EditText)findViewById(R.id.readMessageAuthor);
		EditText sub = (EditText)findViewById(R.id.readMessageSubject);
		EditText text = (EditText)findViewById(R.id.readMessageText);
		author.append(m.getAuthor());
		sub.append(m.getSubject());
		text.append(m.getText());
	}
	
	private String decryptMessage(Message m) {
		return Staaar.stControl.decryptMessage(m.getAuthor(), m.getText());
	}
	
	private String decryptMyMessage(Message m) {
		return Staaar.stControl.decryptMyMessage(m.getText());
	}
	
	private String decryptPrivateMessage(Message m) {
		return Staaar.stControl.decryptPrivateMessage(m.getText());
	}

	private String retrieveMessageText(int id) {
		return Staaar.stControl.retrieveCompleteMessage(id);
	}
}
